import {createRouter, createWebHistory} from "vue-router";
import { useUserStore } from '../stores/userStore.js'
import { ElMessage } from 'element-plus'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        //这里放入路由，例如：
        {
            path: '/',
            component: () => import('../Layout/BasicLayout.vue'),
            children: [
                {
                    name: '虚拟人视频生成',
                    path: '/',
                    component: () => import('../pages/videoGenerate.vue')
                },
                {
                    name: '用户中心页面',
                    path: '/userCenter',
                    component: () => import('../pages/userCenter.vue')
                },
                {
                    name: '用户消息页面',
                    path: '/userMessage',
                    component: () => import('../pages/userMessage.vue')
                },
                {
                    name: '修改个人信息',
                    path: '/editInfo',
                    component: () => import('../pages/editInfo.vue')
                },
                {
                    name: '管理页面',
                    path: '/admin',
                    component: () => import('../pages/adminManage.vue'),
                    meta: { requiresAdmin: true }
                }
            ]
        },
        {
            name: '登录页面',
            path: '/login',
            component: () => import('../components/LoginRegister.vue')
        },
    ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    
    // 检查是否需要管理员权限
    if (to.meta.requiresAdmin) {
        // 检查用户是否已登录
        if (!userStore.user || !userStore.user.id) {
            ElMessage.error('请先登录')
            next('/login')
            return
        }
        
        // 检查用户是否为管理员
        if (userStore.user.role !==1) {
            ElMessage.error('权限不足，只有管理员可以访问此页面')
            next('/')
            return
        }
    }
    
    next()
})

export default router;
